import axios from "axios";

const splicingData = (url,data) => {
   // 准备 url query 参数数据
  let dataStr = '' //数据拼接字符串
  Object.keys(data).forEach(key => {
    dataStr += key + '=' + data[key] + '&'
  })
  if (dataStr !== '') {
    dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
    url = url + '?' + dataStr
  }
  return url
}

export default function ajax(url = '', data = {}, type = 'GET') {
  if (type === 'GET') {
   url =splicingData(url,data)
    // 发送 get 请求
    return axios.get(url)
  } else if (type === "POST") {
    // 发送 post 请求
    return axios.post(url, data) // data: 包含请求体数据的对象
  } else if (type === "DELETE") {
    // 发送 delete 请求
    url = splicingData(url,data)
    return axios.delete(url, data)
  } else if(type === "PUT") {
    return axios.put(url,data)
  } else if(type === "PATCH"){
    return axios.patch(url,data)
  }
}